package com.rslai.commons.validator.jsonvalidator.validate;

import com.rslai.commons.validator.jsonvalidator.JSONSchemaProvider;
import com.rslai.commons.validator.jsonvalidator.JsonSchema;
import com.rslai.commons.validator.jsonvalidator.exception.JSONSchemaException;
import com.rslai.commons.validator.jsonvalidator.schema.Schema;
import com.rslai.commons.validator.jsonvalidator.schema.javacc.JsonParserJavacc;
import com.rslai.commons.validator.jsonvalidator.util.ReaderUtil;
import org.hamcrest.Matchers;
import org.junit.Assert;

import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;

/**
 * JSON Schema代理接口实现类
 */
public class JavaCCSchemaProvider implements JSONSchemaProvider {

    /**
     * 返回JsonSchema
     * @param schema schema字符串
     * @return
     */
    @Override
    public JsonSchema getSchema(String schema) {
        return new JavaCCSchema(getSchemaByJavaCC(schema));
    }

    /**
     * 返回JsonSchema
     * @param schemaStream schema InputStream
     * @return
     */
    @Override
    public JsonSchema getSchema(InputStream schemaStream) {
        String schema = ReaderUtil.reader(schemaStream);
        return new JavaCCSchema(getSchemaByJavaCC(schema));
    }

    /**
     * 返回JsonSchema
     * @param schemaReader schema reader
     * @return
     */
    @Override
    public JsonSchema getSchema(Reader schemaReader) {
        String schema = ReaderUtil.reader(schemaReader);
        return new JavaCCSchema(getSchemaByJavaCC(schema));
    }

    /**
     * 返回JsonSchema
     * @param schemaURL schema URL
     * @return
     */
    @Override
    public JsonSchema getSchema(URL schemaURL) {
        String schema = ReaderUtil.reader(schemaURL);
        return new JavaCCSchema(getSchemaByJavaCC(schema));
    }

    /**
     * 通过JsonParserJavacc返回JsonSchema
     * @param schema schema字符串
     * @return
     */
    private Schema<Object> getSchemaByJavaCC(String schema){
        try {
            Assert.assertThat(schema, Matchers.notNullValue());
            return new JsonParserJavacc(new StringReader(schema)).parse();
        } catch (Exception e) {
            throw new JSONSchemaException("resolve the schema error", e);
        }
    }
}
